﻿#region Using directives
using System;
using System.ComponentModel;
using System.Linq;
using System.Web.Script.Services;
using System.Web.Services;

#endregion

namespace ProcolServices {
    /// <summary>
    /// Summary description for RatingService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    [ScriptService]
    public class RatingService : WebService {
        private readonly ProcolDataContext db = new ProcolDataContext();

        [WebMethod]
        public int GetUserRating(int uid) {
            double? rating = db.UserRatings.Where(s => s.VictimId == uid).Average(s => (double?)s.Score);

            return rating == null ? 0 : (int)Math.Round(rating.Value, MidpointRounding.AwayFromZero);
        }

        [WebMethod]
        public int AddUserRating(int origin, int target, int score) {
            try {
#pragma warning disable 168
                var query = (from r in db.UserRatings
#pragma warning restore 168
                             where r.OriginId == origin && r.VictimId == target && r.Timestamp > DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0))
                             select r).Single();
            } catch (InvalidOperationException) {
                var rating = new UserRating { OriginId = origin, VictimId = target, Timestamp = DateTime.Now, Score = ((byte)score), Reason = "Profile" };

                db.UserRatings.InsertOnSubmit(rating);
                db.SubmitChanges();
            }


            return GetUserRating(target);
        }
    }
}